/***********************************************************************************
**  
* @copyright (c) 2010-2019, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file	    mangjings.cpp
* @version     
* @brief      
* @author   duye
* @date	    2016-12-22
* @note 
*
* 1. 2016-12-22 duye Created this file
*/

#include <duye_system.h>
#include <duye_logger.h>
#include <duye_helper.h>
#include <duye_cfg_mgr.h>
#include <mjs_server.h>

static const int8* DUYE_LOG_PREFIX = "mangjings.main";
static const int8* MJ_LOG_CONF = "/etc/mangjings/conf/mangjings_log.xml";
static const int8* MJ_SYS_CONF = "/etc/mangjings/conf/mangjings.xml";

class ProcessSignal : public duye::ProcessIf {
public:
    ProcessSignal() {}
    virtual ~ProcessSignal() {}

    virtual void onSegFault() {
        DUYE_WARN("process received a segmentation fault, program exit.");
    }

    virtual void onCtrlC() {
        DUYE_WARN("process received exit at Ctrl+C, program exit.");
    }

    virtual void onOther(const int32 sig) {
        DUYE_WARN("process received a signal %d", sig);
    }
};

int main() {
	const int8* process_name = "mangjings";
    if (!DUYE_LOG_INIT(MJ_LOG_CONF))
    {
        printf("%s \n", DUYE_LOG_EDESP());
        return 0;
    }

	DUYE_INFO("process '%s' start", process_name);
 
	duye::ProcessSingle process_single;
	if (process_single.hasProcess(process_name)) {
		DUYE_WARN("process '%s' had a instance, exit.", process_name);
		return 0;
	}

	ProcessSignal process_signal;
	duye::Process::instance().addObserver(&process_signal);
	duye::Process::instance().addSignal(duye::SysProcess::D_SIGINT);

	// load system configuration
	if (!duye::CfgMgr::ins().load(MJ_SYS_CONF)) {
		DUYE_ERROR("load conf:'%s' failed", MJ_SYS_CONF);
		return 0;
	}

	DUYE_INFO("load config : %s [OK]", MJ_SYS_CONF);

	// limit cpu
	uint16 cpu_precent = 100;
	if (!duye::CfgMgr::ins().getValue("node:global.param:cpu_precent", cpu_precent, "value")) {
		DUYE_ERROR("get 'node:global.param:cpu_precent' failed");
		return 0;
	}

	if (!duye::System::limitCpu(process_name, cpu_precent)) {
		DUYE_ERROR("setting limitCpu(%d) failed", cpu_precent);
		return 0;
	}

	DUYE_INFO("setting limit CPU(%d) [OK]", cpu_precent);

	// startup service
	MJServer mj_server;
	if (!mj_server.startup()) {
		mj_server.stop();
		DUYE_ERROR("%s startup failed", process_name);
		return 0;
	}

	DUYE_INFO("%s startup [OK]", process_name);

	while (!duye::Process::instance().wait(2)) {
		DUYE_DEBUG("%s online...", process_name);
	}

	mj_server.stop();

	DUYE_INFO("process '%s' exit", process_name);
	DUYE_LOG_UNINIT();
		
	return 0;
}
